package com.zzgele.qmzb.api.web;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzgele.qmzb.api.core.ResultCode;
import com.alibaba.fastjson.serializer.IntegerCodec;
import com.cnc.cloudv.bean.channel.requestBean.ChannelForbiddenRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.ChannelReBrodcastRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.CreateChannelRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.GetChannelConfigureRequestBean;
import com.cnc.cloudv.bean.channel.responseBean.*;
import com.cnc.cloudv.bean.common.ResponseBean;
import com.cnc.cloudv.live.channelManage.ChannelManage;
import com.github.pagehelper.PageInfo;
import com.zzgele.qmzb.api.Vo.CreateChannelRequestBeanVo;
import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import com.zzgele.qmzb.api.core.ResultGenerator;
import com.zzgele.qmzb.api.model.*;
import com.zzgele.qmzb.api.service.*;
import com.zzgele.qmzb.api.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.zzgele.qmzb.api.core.Constants.PUSH_DOMAIN;

/**
 * Created by Martin on 2017/07/10.
 */
@RestController
@RequestMapping("/room")
public class RoomController {
    private final Logger logger = LoggerFactory.getLogger(RoomController.class);
    @DubboConsumer
    private FocusService focusService;
    @DubboConsumer
    private RoomService roomService;
    @DubboConsumer
    private UserService userService;
    @DubboConsumer
    private FansService fansService;
    @DubboConsumer
    private RoomTypeService roomTypeService;
    @DubboConsumer
    private UserLogService userLogService;
    @DubboConsumer
    private AnchorLogService anchorLogService;
    @DubboConsumer
    private NoticeService noticeService;
    @Resource
    private WatchLogService watchLogService;


    //新主播：创建直播间(以accid做为房间名name)、IM聊天室【以accid做为创建者creator】
    //         accid对应数据表的字段为room.cname/user.im_accid
    @PostMapping("/create")
    public Result create(Long login_uid, String room_title, Integer room_type_id, Integer province_id, Integer city_id, Double lng, Double lat,String uuid) {
        if(!DateUtil.allowLiveBroadcast()) {
            Result result =new Result();
            result.setCode(ResultCode.CHECK_TIME).setMessage("不到开播时间");
            return result;
        }
        if(login_uid==null){
            return ResultGenerator.genFailResult("参数错误");
        }
        List<PullConfigure> list1=null;
        List<PushConfigureInfo> list2=null;
        User user = this.userService.findById(login_uid);

        RoomType roomType = roomTypeService.findById(room_type_id);
        if(roomType == null) {
            return ResultGenerator.genFailResult("参数异常，未知的直播类型！" + room_type_id);
        }
        String room_type = roomType.getTypeName();


        //TODO:临时注释主播认证检测
//        if (user.getUserType() != 1 || user.getAuthenticationStatus() != 2) {
//            return ResultGenerator.genFailResult("你不是认证主播，不能开直播！");
//        }

        String accid = user.getImAccid();

        Room room = roomService.findBy("uid", login_uid);
        if (room == null) {
            //创建聊天室
            //TODO:获取后台最新公告内容
            String announcement = null;
            String ext = "";
//
            String resIm = NeteaseImUtil.chatroomCreate(accid, room_title, announcement, "", ext);

            JSONObject jsonObjIm = JSON.parseObject(resIm);
            Integer codeIm = jsonObjIm.getIntValue("code");
            if(!codeIm.equals(200)) {
                //删除直播间[频道]
//                NeteaseLiveUtil.channelDelete(cid);

                String errorDesc = jsonObjIm.getString("desc");
                logger.warn("IM服务器异常({}):{}", codeIm, errorDesc);
                return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
            }

            JSONObject objectIm = jsonObjIm.getJSONObject("chatroom");
            Long roomId = objectIm.getLongValue("roomid");

            //网易代码end



            room = roomService.insertData(user, login_uid,  room_title,  room_type_id,  province_id,  city_id,  lng,  lat, uuid,room_type,roomId);

        } else {
            //TODO:增加检测状态：直播间[频道]+聊天室

            //更新入库
            room.setTopic(room_title);
            room.setTypeId(room_type_id);
            room.setType(room_type);
            room.setProvinceId(province_id);
            room.setCityId(city_id);
            room.setLng(lng);
            room.setLat(lat);

            room.setPlayStatus(1);
            room.setStatus(Constants.LIVE_STATUS_OPEN); //直播开启
            room.setRoomUserCount(1);
            room.setUpdateTime(DateUtil.getCurUnixTimeStampInt());
            int count = roomService.update(room);
            if(count != 1) {
                logger.warn("数据异常：更新直播间失败！");
                return ResultGenerator.genFailResult("数据异常：更新直播间失败！");
            }
        }

        HashMap hashMap = new HashMap();
        hashMap.put("im_room_id", room.getRoomid());
        hashMap.put("live_push_url", room.getPushUrl());
        hashMap.put("live_rtmp_pull_url", room.getRtmpPullUrl());
        hashMap.put("user_diamond", user.getDiamond());
        hashMap.put("user_ticket", user.getTicket());
        int b=roomService.getTotalTicket( room.getRoomid());
        hashMap.put("ticket_total", b);
        hashMap.put("push_url",room.getPushUrl());// pushConfigureInfoList.get(0).getPushUrl());
        hashMap.put("pull_url",room.getRtmpPullUrl());// pullConfigureList.get(0).getOriginPullUrl());//getPullUrlList().get(0));
        hashMap.put("push_array",room.getPushArray());
        hashMap.put("pull_rtmp_array", room.getRtmpPullArray());
        hashMap.put("pull_hls_array", room.getHlsPullArray());

        //log
        int uid=0;
        if(StringUtils.isNumeric(uuid)){
            uid=Integer.valueOf(uuid);
        }
        AnchorLog anchorLog=new AnchorLog();
        anchorLog.setCreateTime(DateUtil.getCurUnixTimeStampInt());
        anchorLog.setType(1);
        anchorLog.setUid(login_uid);
        anchorLog.setUuid(uid);
        anchorLogService.save(anchorLog);
        JGPush.push(accid,"您的好友"+user.getNickName()+"正在直播间等您聊聊，春宵一刻值千金哦!",user.getIcon(),user.getNickName(),room.getRoomid(),room.getCid(),room.getRtmpPullUrl(),login_uid,"onPlayRemind");
        logger.debug(JSON.toJSONString(hashMap));
        return ResultGenerator.genSuccessResult(hashMap);
    }

    @PostMapping("/join")
    public Result join(Long login_uid, Long roomid,String uuid,Long anchor_uid ) {
        if(roomid==null){
            logger.error("user_join-->uid:{}-->roomid:{}",login_uid,roomid);
            return ResultGenerator.genFailResult("进入房间不详！");
        }
        if(login_uid==null||StringUtils.isBlank(uuid)){
            logger.error("参数错误");
            return ResultGenerator.genFailResult("参数错误");
        }
        int uid=0;
        HashMap hashMap = new HashMap();
        hashMap.put("level", 0);
        if(StringUtils.isNumeric(uuid)){
            uid=Integer.valueOf(uuid);
        }
        HashMap map = new HashMap();
        map.put("roomid", roomid);
        WatchLog watchLog=new WatchLog();
        watchLog.setStartTime(new Date());
        watchLog.setCreateTime(new Date());
        watchLog.setRoomId(roomid);
        watchLog.setUid(login_uid);
        watchLog.setUuid(uid);
        watchLogService.save(watchLog);
        //进入
        map.put("change", 1);
        int b=roomService.getTotalTicket(roomid);
        hashMap.put("ticket_total", b);
        if(anchor_uid!=null) {
            int b2 = roomService.getTotalDiamond(login_uid, anchor_uid);
            hashMap.put("diamond_total",b2 );
        }
        roomService.setInc(map);
        //log
        return ResultGenerator.genSuccessResult(hashMap);
    }
    @PostMapping("/leave")
    public Result leave(Long login_uid, Long roomid,String uuid,Long anchor_uid ) {
        if(roomid==null){
            logger.error("user_leave-->uid:{}-->roomid:{}",login_uid,roomid);
            return ResultGenerator.genFailResult("退出房间不详！");
        }
        if(login_uid==null||StringUtils.isBlank(uuid)){
            logger.error("参数错误");
            return ResultGenerator.genFailResult("参数错误");
        }
        int uid=0;
        HashMap hashMap = new HashMap();
        User user = userService.findById(login_uid);
        hashMap.put("level", user.getLevel());
        if(StringUtils.isNumeric(uuid)){
            uid=Integer.valueOf(uuid);
        }
        HashMap map = new HashMap();
        map.put("roomid", roomid);
        //离开
        map.put("change", -1);
        roomService.setInc(map);

        //统计经验值
        Condition condition=new Condition(UserLog.class);
        condition.createCriteria().andCondition("uid=" + login_uid + " AND uuid=" + uuid);
        HashMap map1=new HashMap();
        map1.put("uid",login_uid);
        map1.put("uuid",uuid);
        WatchLog watchLog=watchLogService.queryByUuid(map1);
        logger.debug("统计经验 : {}",JSON.toJSON(watchLog));
        if(watchLog!=null) {
            //设置离开时间
            watchLog.setEndTime(new Date());
            watchLogService.update(watchLog);
            //计算经验
            int seconds = watchLog.getEndTime().getSeconds() - watchLog.getStartTime().getSeconds();
            logger.debug("seconds : {}",seconds);
            int temp = seconds / 300;
            if (temp > 0) {
                //update
                //score
                long times = userLogService.getTime(String.valueOf(login_uid));
                logger.debug("times : {}",times);
                //每天累计2小时 5minute*24=2hour 五分钟3经验     w
                if (times <= 24) {
                    int temp_new = (times + temp) >= 24 ? 24 : (int) (times + temp);
                    int real_times = (int) (temp_new - times);
                    user.setScoreUser(user.getScoreUser() + real_times * 3);
                    int level = LevelUtil.getLevel(user.getScoreUser());
                    user.setLevel(level);
                    hashMap.put("level", level);
                    userService.update(user);
                    logger.debug("uid{}看直播,得到经验{}",login_uid, real_times * 3);
                }
            }

        }

        //log
        return ResultGenerator.genSuccessResult(hashMap);
    }
    @PostMapping("/live_finish")
    public Result live_finish(Long login_uid,String uuid) {
        Room room = roomService.findBy("uid", login_uid);
        room.setStatus(Constants.LIVE_STATUS_CLOSE);
        roomService.update(room);
        //log
        int uid=0;
        if(StringUtils.isNumeric(uuid)){
            uid=Integer.valueOf(uuid);
        }

        List<AnchorLog> list=anchorLogService.findByConditions(login_uid,uuid);
        AnchorLog anchorLog=new AnchorLog();
        anchorLog.setCreateTime(DateUtil.getCurUnixTimeStampInt());
        anchorLog.setType(1);
        anchorLog.setUid(login_uid);
        anchorLog.setUuid(uid);
        anchorLogService.save(anchorLog);
        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(login_uid);
        fans_count = fansService.selectCount(fans);
        HashMap hashMap=new HashMap();
        hashMap.put("fans_count", fans_count);
        hashMap.put("ticket_total", 0);
        logger.debug("live_finish->  {} {}",login_uid,uuid);
        if(list==null||list.size()<1){
            logger.error("anchorLogService return null");
        } else {
            Integer startTime=list.get(0).getCreateTime();
            int b = roomService.getTheLivingTicket(login_uid,startTime);
            hashMap.put("ticket_total", b);
        }

        return ResultGenerator.genSuccessResult(hashMap);
    }

    @PostMapping("/home")   //首页推荐
    public Result home(Integer page_size) {
        HashMap hashMap = new HashMap();
        //轮播图
        List<HashMap> focusList = focusService.getList(null);
        for(HashMap item:focusList){
            String url=(String)item.get("url");
            String contentPic=(String)item.get("contentPic");
            String newurl=url+"?url="+contentPic;
            item.put("url",newurl);
        }
        hashMap.put("focus_list", focusList);

        if(!DateUtil.allowLiveBroadcast()) {
            hashMap.put("isSeeding", 1); //不允许开播
            //返回条幅
            List<Notice> list = noticeService.getNoticeList(1);
            hashMap.put("notice", list); //预告
            hashMap.put("hotList", new ArrayList<>());
            hashMap.put("list", new ArrayList<>());
            return   ResultGenerator.genSuccessResult(hashMap);

        }
        else
            hashMap.put("isSeeding", 0); //允许开播



        List<HashMap> officialList =new ArrayList<>();// roomService.getOfficialList(map1);
        hashMap.put("official_list", officialList);

        List<HashMap> hotList =roomService.getOfficialList();
        hashMap.put("hotList", hotList);

        return ResultGenerator.genSuccessResult(hashMap);
    }


    //TODO:已作废
    @PostMapping("/home_list")
    public Result homeList(Integer page,Integer page_size) {
        page = page<2 ? 2 : page; //至少第二页

        PageUtil.startPage(page, page_size);
        HashMap map = new HashMap();
        map.put("room_status", 1);
        map.put("order", "u.hot_desc DESC,room.id ASC");
        map.put("page", page);
        map.put("page_size",page_size);
        List<HashMap> roomList = roomService.getLists(map);
        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));

        return ResultGenerator.genSuccessResult(roomListHashMap);
    }
    @PostMapping("/forbidden")
    public Result forbidden(Long login_uid, Long roomid) {
        Room room = roomService.findBy("uid", login_uid);
        if(room==null)
            return ResultGenerator.genFailResult("room is null");
        ChannelForbiddenRequestBean bean=new ChannelForbiddenRequestBean();
        bean.setPullId(room.getCid());
        try {
//            ResponseBean responseBean=channelManage.channelForbidden(bean);
            ResponseBean responseBean = roomService.channelForbidden(bean);
            if(responseBean.getCode()==200){
                logger.info("forbidden info--->",responseBean);
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        return ResultGenerator.genFailResult("error");
    }
    @PostMapping("/reBroadcast")
    public Result reBroadcast(Long login_uid, Long roomid) {
        Room room = roomService.findBy("uid", login_uid);
        if(room==null)
            return ResultGenerator.genFailResult("room is null");
        ChannelReBrodcastRequestBean bean=new ChannelReBrodcastRequestBean();
        bean.setPullId(room.getCid());
        try {
            ResponseBean responseBean= roomService.channelReBrodcast(bean);
//            ResponseBean responseBean=channelManage.channelReBrodcast(bean);
            if(responseBean.getCode()==200){
                logger.info("reBroadcast info--->",responseBean);
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        return ResultGenerator.genFailResult("error");
    }
    @PostMapping("/new_list")  //最新列表
    public Result typeList(Integer page,Integer page_size) {

        HashMap map = new HashMap();
        if(!DateUtil.allowLiveBroadcast()) {
            map.put("isSeeding", 1); //不允许开播
            //返回条幅
            List<Notice> list = noticeService.getNoticeList(2);
            map.put("notice", list); //预告
            map.put("page", 0);
            map.put("pages", 0);
            map.put("hasNextPage", 0);
            map.put("list", new ArrayList<>());
            return   ResultGenerator.genSuccessResult(map);

        }
        else
            map.put("isSeeding", 0); //允许开播



        map.put("room_status", 1);
        map.put("order", "a.id DESC");
        map.put("page",page);
        map.put("page_size",page_size);
        List<HashMap> roomList = roomService.getLists(map);

        /**
         * 限制直播间人数小于0时，默认初始化为0
         * 修改人：常扬
         * 修改时间：201710201636
         */
        for(HashMap hashMap : roomList) {
            if(hashMap.get("room_user_count") != null){
                Object rusObj = hashMap.get("room_user_count");
                int rusInt = (int) rusObj;
                if(rusInt < 0)
                    hashMap.put("room_user_count", 0);
            }
        }
        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));
        roomListHashMap.put("isSeeding", 0); //允许开播
        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

    @PostMapping("/type_list")
    public Result typeList(Integer type_id,Integer page,Integer page_size) {
        PageUtil.startPage(page, page_size);
        HashMap hashMap = new HashMap();
        if(!DateUtil.allowLiveBroadcast()) {
            hashMap.put("isSeeding", 1); //不允许开播
            //返回条幅
            List<Notice> list = noticeService.getNoticeList(3);
            hashMap.put("notice", list); //预告
            hashMap.put("page", 0);
            hashMap.put("pages", 0);
            hashMap.put("hasNextPage", 0);
            hashMap.put("list", new ArrayList<>());
            return  ResultGenerator.genSuccessResult(hashMap);
        }


        hashMap.put("room_status", 1);
        hashMap.put("type_id", type_id);
        List<HashMap> roomList = roomService.getList(hashMap);
        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));
        roomListHashMap.put("isSeeding", 0); //允许开播

        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

    @PostMapping("/city_list")
    public Result cityList(Integer province_id,Integer city_id,Integer page,Integer page_size) {
        PageUtil.startPage(page, page_size);
        HashMap hashMap = new HashMap();
        if(!DateUtil.allowLiveBroadcast()) {
            hashMap.put("isSeeding", 1); //不允许开播
            //返回条幅
            List<Notice> list = noticeService.getNoticeList(4);
            hashMap.put("notice", list); //预告
            hashMap.put("page", 0);
            hashMap.put("pages", 0);
            hashMap.put("hasNextPage", 0);
            hashMap.put("list", new ArrayList<>());
            return  ResultGenerator.genSuccessResult(hashMap);
        }

        hashMap.put("room_status", 1);
        hashMap.put("province_id", province_id);
        hashMap.put("page",page);
        hashMap.put("page_size",page_size);
        //map.put("city_id", city_id);
        List<HashMap> roomList = roomService.getLists(hashMap);
        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));
        roomListHashMap.put("isSeeding", 0); //允许开播

        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

    @PostMapping("/distance_list")
    public Result distanceList(Double lng,Double lat,Integer page,Integer page_size) {
        //logger.info("lng：{} lat：{}",lng, lat);

        HashMap hashMap = new HashMap();
        if(!DateUtil.allowLiveBroadcast()) {
            hashMap.put("isSeeding", 1); //不允许开播
            //返回条幅
            List<Notice> list = noticeService.getNoticeList(5);
            hashMap.put("notice", list); //预告
            hashMap.put("page", 0);
            hashMap.put("pages", 0);
            hashMap.put("hasNextPage", 0);
            hashMap.put("list", new ArrayList<>());
            return ResultGenerator.genSuccessResult(hashMap);

        }



        Map<String, Object> map = new HashMap();
        map.put("room_status", 1);
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("page",page);
        map.put("page_size",page_size);
        List<HashMap> roomList= roomService.getListByDistance(map);

        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));
        roomListHashMap.put("isSeeding", 0); //允许开播
        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

    @PostMapping("/follow_list")
    public Result followList(Long login_uid,Integer page,Integer page_size) {
        Map<String, Object> mapFans = new HashMap();
        mapFans.put("fans_uid", login_uid);
        List<HashMap> followList = fansService.getList(mapFans);

        //用户关注主播的uid
        List followUserIdList = new ArrayList();
        for(HashMap map:followList){
            followUserIdList.add(map.get("uid"));
        }
        String followUserIds = StringUtil.implode(followUserIdList, ",");
        //logger.info(followUserIds);

        if(!StringUtil.isEmpty(followUserIds)) {
            //避免出现null
            followUserIds = "0";
        }

        PageUtil.startPage(page, page_size);
        Map<String, Object> map = new HashMap();
        map.put("follow_user_ids", followUserIds);
        map.put("room_status", 1);
        List<HashMap> roomList= roomService.getList(map);

        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(roomList));

        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

}
